package com.zd.bms.filter;

import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zd.bms.service.IBmsResourceService;
import com.zd.bms.service.ISysLogService;
import com.zd.common.bean.model.BmsUser;
import com.zd.common.bean.model.SysLog;
import com.zd.common.common.utils.EncryptUtil;

public class SessionFilter implements Filter {
	private ISysLogService sysLogService;
	private IBmsResourceService bmsResourceService;

	public FilterConfig config;

	@Override
	public void destroy() {
		config = null;

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;//获取request对象
		HttpServletResponse response = (HttpServletResponse) arg1;//获取response对象
		Cookie[] cookies = request.getCookies();//获取cookie对象
		String url = request.getRequestURI();
		String resource = url.replace(request.getContextPath(), "");
		if ("".equals(resource.trim())) {
			arg2.doFilter(request, response);
			return;
		}
		String noFilter = config.getInitParameter("noFilter");//放行的网页
		String[] data = noFilter.split(";");
		for (String string : data) {
			if (resource.equals(string)) {
				arg2.doFilter(request, response);
				return;
			}
		}
		String staticName = config.getInitParameter("static");
		String[] statics = staticName.split(";");
		for (String string : statics) {
			if (resource.startsWith(string)) {
				arg2.doFilter(request, response);
				return;
			}
		}

		BmsUser bmsUser = null;
		if (cookies == null) {
			response.sendRedirect(request.getContextPath() + "/index/login");
			return;
		}
		for (Cookie cookie : cookies) {
			if ("user".equals(cookie.getName())) {
				try {
					bmsUser = JSONObject.parseObject(EncryptUtil.deBase64(cookie.getValue()), BmsUser.class);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		if (bmsUser == null) {
			response.sendRedirect(request.getContextPath() + "/index/login");
			return;
		}

		Set<String> resourceList = new HashSet<>();
		for (Cookie cookie : cookies) {
			if ("resourceList".equals(cookie.getName())) {
				JSONArray resourceJSONArray;
				try {
					resourceJSONArray = JSONArray.parseArray(EncryptUtil.deBase64(cookie.getValue()));
					for (Object resourceJSON : resourceJSONArray) {
						resourceList.add(resourceJSON.toString());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		for (String string : resourceList) {
			if (resource.equals(string)) {//判断是否符合用户权限的网页
				try {
					if (!resource.toLowerCase().contains("index") && !resource.toLowerCase().contains("list")
							&& !resource.toLowerCase().contains("get")) {
						// 记录日志
						SysLog sysLog = new SysLog();
						sysLog.setActionUri(resource);
						sysLog.setScenicSpotId(bmsUser.getScenicSpotId());
						sysLog.setUserId(bmsUser.getId());
						sysLog.setUserEntNo(bmsUser.getEntNo());
						sysLog.setActionName(bmsResourceService.getFullUriName(resource));
						Map<String, String[]> parameterMap = request.getParameterMap();
						sysLog.setParams(JSONObject.toJSON(parameterMap).toString());
						sysLog.setCreateTime(new Date());
						sysLog.setUpdateTime(new Date());
						sysLogService.insert(sysLog);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				arg2.doFilter(request, response);
				return;
			}
		}
		response.sendRedirect(request.getContextPath() + "/static/plug/page/power.jsp");
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		config = arg0;
		WebApplicationContext cxt = (WebApplicationContext) arg0.getServletContext()
				.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		if (cxt != null) {
			if (sysLogService == null) {
				sysLogService = (ISysLogService) cxt.getBean("sysLogServiceImpl");
			}

			if (bmsResourceService == null) {
				bmsResourceService = (IBmsResourceService) cxt.getBean("bmsResourceServiceImpl");
			}
		}
	}
}
